var express = require('express');
var router = express.Router();
var AipFaceClient = require("baidu-aip-sdk").face;
var HttpClient = require("baidu-aip-sdk").HttpClient;
let multiparty = require('multiparty');
HttpClient.setRequestOptions({ timeout: 5000 });
// 设置APPID/AK/SK
const APP_ID = "115840474"
const API_KEY = "c2Mi9SKSvx1v6zvRnPfBBpgZ"
const SECRET_KEY = "9q9WinIp1g1zacahlkTmcRjTkqAyE6F7"
// 新建一个对象，建议只保存一个对象调用服务接口
var client = new AipFaceClient(APP_ID, API_KEY, SECRET_KEY);
let faceVerificationWithLiveness = async (image) => {
    try {
        const detectResult1 = await client.faceverify([
            {
                image: image,
                image_type: 'BASE64'
            }]).then(function (result) {
                // console.log(result);
                return result
            });
        const isLive1 = detectResult1 && detectResult1.result && detectResult1.result.face_list && detectResult1.result.face_list.length > 0 && detectResult1.result.face_liveness > 0.9;
        if (!isLive1) {
            console.log('活体检测失败')
            return 400;
        }
        var imageType = "BASE64";
        var groupIdList ="m200589";
        //调用人脸搜索
        const detectResult2 = await client.search(image, imageType, groupIdList).then(function (result) {
           
            console.log(result);
            return result
        }).catch(function (err) {
            // 如果发生网络错误
            console.log(err);
        });
        if(detectResult2.error_code===0&&detectResult2.result.user_list[0].score>80){
            console.log('人脸验证成功')
            return 200;
        }else{
            console.log('人脸验证失败')
            return 402;
        }

    } catch (err) {
        console.error("人脸验证或活体检测过程中发生错误:", err);
        return 500;
    }
}
router.post('/face-verification', async (req, res) => {
    
    let form = new multiparty.Form();
    form.uploadDir = "upload"
    form.parse(req, (err, imgData, fileData) => {
        // console.log(imgData)
        const name = imgData.name[0]
        const file = imgData.file[0]
        let filepath = "./upload/" + name
        const base64Image = file.replace(/^data:image\/png;base64,/, "");
        // console.log(base64Image);
        
         faceVerificationWithLiveness(base64Image).then(code=>{
            console.log(code)
            if(code===200){
                res.send({
                    code: 200,
                    message: '人脸验证成功'
                })
            }else if(code===400){
                res.send({
                    code: 400,
                    message: '活体检测失败'
                })
            }else if(code===402){
                res.send({
                    code: 402,
                    message: '人脸验证失败'
                })
            }
        })
    })

    // const {image} = req.body;
    
});

module.exports = router;
